import os
import json
from random import randint
from datetime import datetime
from pathlib import Path
from openai import OpenAI
from api import kimi
from log import log
client = OpenAI(
            api_key="sk-HrSOhl9oIvJKZqcdiqGaYqu6tXMXzA28sJeRRV7Wrejt3WqG",
            base_url="https://api.moonshot.cn/v1",
        )

def kimi_file(self, file_path, question):
    file_object = self.client.files.create(file=Path(file_path), purpose="file-extract")
    file_id = file_object.id
    file_content = self.client.files.content(file_id=file_id).text
    messages = [
        {
            "role": "system",
            "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。",
        },
        {
            "role": "system",
            "content": file_content,
        },
        {"role": "user", "content": question},
    ]
    completion = self.client.chat.completions.create(
        model="moonshot-v1-32k",
        messages=messages,
        temperature=0.1,
    )
    self.client.files.delete(file_id=file_id)
    return completion.choices[0].message.content

def creat_prompt(excel_file,user_input):
    question = '提取表格中所需要填写的字段，输出格式为json，{\"需要填写的字段\": [XXX,XXX]} 只用输出json，其他都不用输出'
    if Path(excel_file).exists():
        try:
            k = kimi.kimi_file(file_path=excel_file, question=question)
            print(f"kimi提取填表的字段内容：{k}")
            log.info(f"kimi提取填表的字段内容：{k}")
            r_k = k.replace("```json", "").replace("```", "")
            k_json = json.loads(r_k)
            columns =[str(i).strip() for i in  k_json["需要填写的字段"]]
            prompt = user_input + "相关的"+",".join(columns) + "的信息"
        except Exception:
            print(f"kimi抽取文章失败---{Exception}")
            log.error(f"kimi抽取文章失败---{Exception}")
            prompt = user_input
            columns = []
    else:
        prompt = user_input+"，注意去重"
        columns = []
    print(f"生成的prompt：{prompt}")
    log.info(f"生成的prompt：{prompt}")
    print(f"提取表格中需要填写的字段：{columns}")
    log.info(f"提取表格中需要填写的字段：{columns}")
    return prompt,columns

def to_execl(res):
    pwd = os.getcwd()
    save_path = os.path.join(pwd, "out_file",datetime.now().strftime("%Y%m%d_%H%M%S_") + str(randint(0, 1000)) + ".xlsx")
    print(save_path)
    log.info(f"文件保存的位置是：{save_path}")
    res.to_excel(save_path,index=False)
    return Path(save_path).stem

if __name__ == '__main__':
    path = os.path.join(os.getcwd(),"user_file","c.xlsx")
    print(Path(path).exists())
    creat_prompt(path,"刘芳负责项目")
